from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import redirect
from django.urls import reverse
from django.core.paginator import Paginator
from datetime import datetime
from common.models import Vip


def index(request, pIndex=1):
    '''浏览信息'''
    list1 = Vip.objects.all()
    # 执行分页处理
    pIndex = int(pIndex)
    page = Paginator(list1, 12)  # 以12条每页创建分页对象
    maxpages = page.num_pages  # 最大页数
    # 判断页数是否越界
    if pIndex > maxpages:
        pIndex = maxpages
    if pIndex < 1:
        pIndex = 1
    list2 = page.page(pIndex)  # 当前页数据
    plist = page.page_range  # 页码数列表
    px = pIndex
    plist2 = set()
    plist2.add(px)
    for x in range(1, 6):
        if px - x >= 1 and len(plist2) <= 11:
            plist2.add(px - x)
        if px + x <= maxpages and len(plist2) <= 11:
            plist2.add(px + x)

    plist2 = list(plist2)
    plist2.sort()

    context = {"userslist": list2, 'plist': plist2, 'pIndex': pIndex, 'maxpages': maxpages}

    return render(request, "myadmin/vip/index.html", context)


def add(request):
    '''加载添加页面'''
    return render(request, "myadmin/vip/add.html")


def insert(request):
    '''执行添加'''
    try:
        ob = Vip()
        ob.username = request.POST['username']
        # 判断用户名是否重复
        flag = Vip.objects.filter(username=ob.username)
        if flag:
            context = {"info": "该用户名已被注册！"}
            return render(request, "myadmin/vip/info.html", context)
        ob.password = request.POST['password']
        ob.state = 1
        ob.addtime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {"info": "添加成功！"}
    except Exception as err:
        print(err)
        context = {"info": "添加失败！"}
    return render(request, "myadmin/vip/info.html", context)


def delete(request, uid):
    '''删除信息'''
    try:
        ob = Vip.objects.get(id=uid)
        ob.delete()
        context = {"info": "删除成功！"}
    except Exception as err:
        print(err)
        context = {"info": "删除失败！"}
    return render(request, "myadmin/vip/info.html", context)


def edit(request, uid):
    '''加载编辑信息页面'''
    try:
        ob = Vip.objects.get(id=uid)
        context = {"user": ob}
        return render(request, "myadmin/vip/edit.html", context)
    except Exception as err:
        context = {"info": "没有找到要修改的信息"}
    return render(request, "myadmin/vip/info.html", context)


def update(request, uid):
    '''执行编辑信息'''
    try:
        ob = Vip.objects.get(id=uid)
        ob.username = request.POST['username']
        ob.password = request.POST['password']
        ob.save()
        context = {"info": "修改成功！"}
    except Exception as err:
        print(err)
        context = {"info": "修改失败！"}
    return render(request, "myadmin/vip/info.html", context)
